﻿using Microsoft.EntityFrameworkCore;
using SCZS.Example.Core.Helper;
using SCZS.Example.DTOModel;
using SCZS.Example.IService;
using SCZS.Example.Model.Example;

namespace SCZS.Example.Service
{
    public class UserService : IUserService
    {
        private ExampleContext _exampleContext;
        public UserService(ExampleContext exampleContext)
        {
            _exampleContext = exampleContext;

        }


        /// <summary>
        /// 根据账号密码查询用户
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<Output<SysUserInfo>> QueryUser(string userAccount, string password)
        {
            Output<SysUserInfo> output = new Output<SysUserInfo>();
            //首先根据用户名查询用户
            SysUserInfo user = await _exampleContext.SysUserInfos.Where(m => m.UserAccount == userAccount).FirstOrDefaultAsync();

            if (user == null)
            {
                output.IsSuccess = false;
                output.Message = "查询的用户不存在！";
                return output;
            }

            if (MD5Helper.MD5EncodingWithSalt(password, user.Salt) != user.Password)
            {
                //密码不正确
                output.IsSuccess = false;
                output.Message = "密码错误";
                return output;
            }
            output.Data = user;
            return output;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="user"></param>
        /// <param name="code"></param>
        public async Task<Output> Register(SysUserInfo user, string code)
        {
            Output output = new Output();
            user.Salt = MD5Helper.MD5EncodingOnly(user.UserAccount);
            string md5Pwd = MD5Helper.MD5EncodingWithSalt(user.Password, user.Salt);
            user.Password = md5Pwd;
            _exampleContext.Add(user);
            int count =await _exampleContext.SaveChangesAsync();
            if (count != 1)
            {
                output.IsSuccess = false;
                output.Message = "用户注册失败";
                return output;
            }

            return output;
        }

    }
}